﻿using Csb.SignalServer.Model;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Net.Http.Json;
using System.Text.Json.Serialization;

namespace Csb.SignalServer.Hubs
{
    public class ChatHub : Hub
    {
        private static readonly ConcurrentDictionary<string, User> ChatClientDict = new(); //用户字典

        /// <summary>
        /// 给所有人发消息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public async Task SendMsg(long userId, string msg)
        {
            string sendMsg = $"用户名{Context.ConnectionId}：{msg}";

            //服务端推送给 除自已以外 的所有客户端
            //await Clients.Others.SendAsync("ReceiveMsg", sendMsg);

            //服务端推送给所有客户端
            await Clients.All.SendAsync("ReceiveMsg", sendMsg);

        }

        /// <summary>
        /// 给指定人员发消息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public async Task SendMessageToUser(string userId, string message)
        {
            // 确保用户ID是有效的
            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentException("Invalid user ID", nameof(userId));
            }
            await Clients.Client(userId).SendAsync("ReceiveToUserMsg", message);
        }

        //客户端成功连接时，会触发此方法
        public override async Task OnConnectedAsync()
        {
            //var cid = Context.ConnectionId;
            ////根据id获取指定客户端
            //var client = Clients.Client(cid);
            
            var userName = ChatClientDict.SingleOrDefault((c) => c.Value.Id == Context.ConnectionId).Key;
            if (string.IsNullOrWhiteSpace(userName))
            {
                //Clients.Users(userName);
                ChatClientDict.TryAdd(Context.ConnectionId, new User { UserName = "123", UserPassord = "456",Id = Context.ConnectionId });
            }
            Console.WriteLine($"{Context.ConnectionId} 已连接");


            await Clients.All.SendAsync("UpdateUserList", ChatClientDict.Values.ToArray());
            await Clients.All.SendAsync("UpdateOnlineCount", ChatClientDict.Values.Count);
            await base.OnConnectedAsync();

            //return base.OnConnectedAsync();
            //return Task.CompletedTask;
        }

        //客户端断开连接时，会触发此方法
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            var userName = ChatClientDict.SingleOrDefault((c)=>c.Value.Id == Context.ConnectionId).Key;
            if (!string.IsNullOrWhiteSpace(userName))
            {
                ChatClientDict.Remove(userName,out _);             
            }
            Console.WriteLine($"{Context.ConnectionId} 已断开: {exception?.Message}");

            await Clients.All.SendAsync("UpdateUserList", ChatClientDict.Values.ToArray());
            await Clients.All.SendAsync("UpdateOnlineCount", ChatClientDict.Values.Count);
            await base.OnDisconnectedAsync(exception);

            //return base.OnDisconnectedAsync(exception);
            //return Task.CompletedTask;
        }

        //客户端调用服务端更新数据时，会触发此方法
        public async Task UpdateMessage(MsgInfo ReceiveMessage)
        {
            await Clients.All.SendAsync("UpdateData", ReceiveMessage);
        }


        //登录功能
        public async Task Login(User user)
        {
            try
            {
                string userId = user.Id;
                var userList = new List<User>();
                if (string.IsNullOrWhiteSpace(userId))
                {
                    //return new Tuple<bool, List<User>>(false, userList);
                    await Task.CompletedTask;
                    return;
                }

                Console.WriteLine($"{Context.ConnectionId} 登录");

                if (!ChatClientDict.ContainsKey(userId))
                {
                    userList.AddRange(ChatClientDict.Values);

                    var newUser = new User { UserName = user.UserName, Id = Context.ConnectionId, UserPassord = user.UserPassord };

                    var add = ChatClientDict.TryAdd(userId, newUser);
                    if (!add)
                    {
                        userList.Clear();
                        //return new Tuple<bool, List<User>>(false, userList);
                    }
                    await Clients.All.SendAsync("ReceiveLoginMsg", new MsgInfo { user = JsonConvert.SerializeObject(newUser), message = "登录成功" });
                }
                else
                {
                    var userModel = ChatClientDict[userId];
                    userList.AddRange(ChatClientDict.Values.Where(t => t.Id != userId));
                }

                //return new Tuple<bool, List<User>>(true, userList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public async Task LoginOut(string userId)
        {
            if (string.IsNullOrWhiteSpace(userId))
            {
                return;
            }
            Console.WriteLine($"{userId} 退出");

            ChatClientDict.TryRemove(userId, out _);
            await Clients.User(userId).SendAsync("ReceiveLoginOutMsg", "退出成功");
        }





    }
}
